<template>
  <view>
    <div class="goods-list">
      <view v-for="(goods,index) in goodsList" :key="goods.goods_id" @click="gotoDetail(goods.goods_id)">
        <my-goods :goods="goods"></my-goods>
      </view>
    </div>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        // 请求参数对象
        queryObj: {
          query: '',
          cid: '',
          pagenum: 1,
          pagesize: 10
        },
        // 商品列表数据
        goodsList: [],
        // 总记录数
        total: 0,
        // 节流阀：是否正在请求数据
        isloading: false
      };
    },
    onLoad(options) {
      // 接收页面参数
      this.queryObj.query = options.query || '';
      this.queryObj.cid = options.cid || '';
      // 获取商品列表数据
      this.getGoodsList();
    },
    methods: {
      // 获取商品列表数据
      async getGoodsList(callback) {
        // 打开节流阀
        this.isloading = true;
        // 发送请求获取数据
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj);
        // 关闭节流阀
        this.isloading = false;
        // 调用回调函数: 主要用于关闭下拉刷新
        callback && callback();
        if (res.meta.status !== 200) return uni.$showMsg();
        this.goodsList = [...this.goodsList, ...res.message.goods];
        this.total = res.message.total;
      },
      // 点击每一个商品数据项时的事件处理函数
      gotoDetail(id) {
        // 跳转到指定的商品详情页
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + id
        })
      }
    },
    // 页面触底事件: 实现加载更多数据
    onReachBottom() {
      // 判断数据是否加载完毕
      if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg("数据加载完毕");
      // 节流：如果正在请求则不许再次请求
      if (this.isloading) return;
      // 让页码值自增
      this.queryObj.pagenum++;
      // 重新获取商品数据
      this.getGoodsList();
    },
    // 页面下拉事件：实现下拉刷新
    onPullDownRefresh() {
      // 重置关键数据
      this.queryObj.pagenum = 1;
      this.total = 0;
      this.isloading = false;
      this.goodsList = [];
      // 重新发起请求获取数据
      this.getGoodsList(() => uni.stopPullDownRefresh());
    }
  }
</script>

<style lang="scss" scoped>
  .goods-list {
    background-color: #fff;

    .goods-item {
      display: flex;
      padding: 10px 5px;
      border-bottom: 1px solid #f0f0f0;

      .goods-item-left {
        margin-right: 5px;

        .goods-pic {
          display: block;
          width: 100px;
          height: 100px;
        }
      }

      .goods-item-right {
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .goods-name {
          font-size: 13px;
        }

        .good-info-box {
          .goods-price {
            color: #c00000;
            font-size: 16px;
          }
        }
      }
    }
  }
</style>
